<?php

namespace app\game\controller;
use cmf\controller\UserBaseController;
use think\Db;
use think\Request;
/**
 * 游戏打包逻辑处理
 *
 * @author sipeng
 */
class GamehandlerController extends UserBaseController{
    private $sensitiveFields = ['price', 'order_status', 'is_complate'];
    private $promptmessageConfig = [
        'appName'=> '应用名称长度建议应为2~4个字符',
        'version'=>'金币余额：介绍描述。 房卡：介绍描述。  金币+房卡：介绍描述。 1:1：介绍描述。',
        'platform'=>'选择将要打包的平台版本'
    ];

    public function getGameList(){
    	$post = Request::instance()->param();
        $pageNum = isset($post["pageNum"]) ? $post["pageNum"] : 1;
    	$data = Db::name('game_list')->where('enable_i',1)->order('id desc')->limit(($pageNum - 1) * 5 . ',' . 5)->select();
    	$total = Db::name('game_list')->count();
        $pdata = ['list'=>$data, 'total'=>$total];
    	$this->result($pdata,1,'请求成功','json',[], 'status');
    }
    public function saveStep(){      
    	$param = Request::instance()->param();	
		$userStep = Db::name('game_build')->where(['user_id'=>$this->user['user_id'], 'is_complete'=>0])->select();   
		$noTokenParams = $this->removeArrayItemByName($param, 'token');
        $stepId = $param['stepId'];
        $newParam = $this->removeArrayItemByName($noTokenParams, 'stepId');
        $plat_id = isset($newParam['plat_id']) ? $newParam['plat_id'] : '';
        $newParams = $this->removeArrayItemByName($newParam, 'plat_id');
        $result = -1;
        $filterdFields = $this->fieldsFilter($this->sensitiveFields, $newParams);

		if(sizeof($userStep) > 0){
			Db::name('game_build')
                ->where('id', $stepId)
                ->update($filterdFields);
            $isComplete = isset($param['is_complete']) ? ($param['is_complete'] == 1 ? true : false) : false;   
            if($isComplete) {
                $this->calcTotalPrice($param, $stepId);
                Db::name('game_build')->where('id', $stepId)->update(['is_complete'=>1]);
            };

            // 向packet表中添加数据
            $packageList = Db::name('packet')->where(['buildid'=>$stepId])->find();
            if($isComplete){
                if(sizeof($packageList) > 0){
                    $vlist = explode('.', $packageList['version']);
                    $v = intval($vlist[2]) + 1;
                    Db::name('packet')->where(['buildid'=>$stepId])->update(['version'=> '0.0.'.$v, 'plat_id'=> $plat_id]);
                }else{
                    $def_conf = Db::name('system_setting')->where(['key_m'=>'package_version'])->find();
                    Db::name('packet')->insert(
                        [
                         'version'  => $def_conf['value_m'],
                         'plat_id'  => $plat_id, 
                         'build_dt' => date("Y/m/d h:i:s"),
                         'buildid'  => $stepId
                        ]
                    );
                }    
            }
		}else{
			$result = Db::name('game_build')->insertGetId(
				array_merge(
                    ['user_id'=>$this->user['user_id']], $filterdFields, ['is_complete'=>0], 
                    ['create_dt'=> date("Y/m/d h:i:s")]
                )
			);
		}
        $this->result(['id'=>$result],1,'修改状态成功','json',[],'status');
    }
    // 过滤敏感字段
    private function fieldsFilter($filters, $fields){
        $result = [];
        foreach($filters as $key => $v){
            foreach ($fields as $key => $value) {
                if(!isset($fields[$v])){
                   $result[$key] = $value;
                }
            }
        }
        return $result;
    }
    private function calcTotalPrice($param, $stepId, $server = null){

        $totalPrice = 0;
        $resourceList = [
            $param['logo_id'], 
            $param['theme_id'],
            $param['loading_id'],
            $param['icon_id']
        ];
        $resourceTotalPrice = 0;
        foreach ($resourceList as $value) {
            $resourceTotalPrice += $this->getResourcePrice(['id'=>$value]);
        }

        $gameTotalPrice = 0;
        $idArray = explode(',', $param['game_ids']);
        foreach ($idArray as $value) {
            $gameTotalPrice += $this->getGameListPrice(['id'=>$value]);
        }

        Db::name('game_build')->where('id', $stepId)
        ->update(['price'=>round(
            $gameTotalPrice + $resourceTotalPrice + (($server && $server['serverFlag']) ? $server['price'] : 0), 2)]
        );
    }
    private function getResourcePrice($where){
        $result = Db::name('game_resource')->where($where)->find();
        if(isset($result)) return $result['price'];
        else 0;
    }
    private function getGameListPrice($where){
        $result = Db::name('game_list')->where($where)->find();
        if(isset($result)) return $result['price'];
        else 0;   
    }
    public function getGameDetail () {
        $params = Request::instance()->param();
        $id = isset($params['id']) ? $params['id'] : false;
        if(!$id) return $this->result([],0,'ID不能为空','json',[],'status');
        $gameList = Db::name('game_build')->where(['id'=>$id])->select();

        if(sizeof($gameList) < 1) return $this->result([],0,'ID有误!','json',[],'status');
        $result = $this->queryImageResource($gameList, ['logo_id','theme_id','loading_id','icon_id']);
        foreach ($result as $key => $value) {
            $result[$key]['gamelist'] = $this->queryGameListById($result[$key]['game_ids']);
        }
        $this->result($result,1,'请求成功','json',[],'status');
    }

    public function getChildrenGameList(){
        $params = Request::instance()->param();
        $id = isset($params['id']) ? $params['id'] : false;
        if(!$id) return $this->result([],0,'ID不能为空','json',[],'status');
        $gameList = Db::name('game_build')->field(['game_list', 'game_ids', 'server_id'])->where(['id'=>$id])->find();       
        if(sizeof($gameList) < 1) return $this->result([],0,'ID有误!','json',[],'status');
        
        $r = $this->queryGameListById($gameList['game_ids']);        
        foreach ($r as $key => $value) {
            $r[$key]['server_id'] = $gameList['server_id'];
        }
        $this->result($r,1,'请求成功','json',[],'status');
    }
    private function queryGameListById ($ids){
        $idArray = explode(',', $ids);
        $result = [];
        foreach ($idArray as $value) {
            if($value){
                $game = Db::name('game_list')->where(['id'=>$value])->find();
                array_push($result, $game);    
            }
        }
        return $result;
    }
    /**
     * 通过key删除数组中元素
     * @param  $arrays 操作数据
     * @param  $itemName 删除key
     * @return 移除后指定key后的数组
     */
    protected function removeArrayItemByName ($arrays, $itemName){
        $keys = array_keys($arrays); 
        $index = array_search($itemName, $keys); 
        if($index !== false){
           array_splice($arrays, $index, 1); 
        }
        return $arrays;
    }

    public function getStep(){
		$param = Request::instance()->param();
        $queryWhere = [];
        $plat_id = null;
        if(isset($param['id'])){
            $queryWhere = ['user_id'=> $this->user['user_id'], 'id'=>$param['id']];
            $b = Db::name('packet')->where(['buildid'=>$param['id']])->find();
            $plat_id = $b['plat_id']; 
        }else{
            $queryWhere = ['user_id'=> $this->user['user_id'], 'is_complete'=>0];
        }


		$result = Db::name('game_build')->where($queryWhere)->find();

        if($plat_id){
          $result['plat_id'] = $plat_id;
        }
		$this->result($result,1,'请求成功','json',[], 'status');
    }

    public function getServerConfigInfo(){
        $data = Db::name('esc_price')->select();
        $result = ['place'=>[],'people_num'=>[], 'server_time'=>[]];
        foreach ($data as $key => $value) {
            array_push($result['place'], [
                'name'=>$data[$key]['place_name'],
                'value'=> $data[$key]['place'],
                'desc'=>$data[$key]['place_desc']
            ]);
        }
        $result['people_num'] = $this->addFields($data);   
        $result['server_time'] = $this->resolveServerTimeData($data);
        $this->result($result,1,'请求成功','json',[],'status');
    }

    private function resolveServerTimeData($data){
        $result = [];
        foreach ($data as $key => $value) {
            $timeItems = explode(';', $data[$key]['server_time']);
            foreach ($timeItems as $value) {
                $time = explode(':', $value);
                if(sizeof($time) !== 1){
                    array_push($result, [
                        'name'=> $time[0],
                        'value'=> $time[1],
                    ]);
                }
            }
        }

        return $result;
    }

    public function getServerListByUserId (){
        $param = Request::instance()->param();
        if(!isset($param['game_id'])) return $this->result([],0, '参数不完整!', 'json',[], 'status');
        $unbindServerList = Db::name('server')->where(
            [
                'user_id'=>$this->user['user_id'],
                'is_bind'=>0
            ]
        )->select();
        $bindServerList = Db::name('server')->where(
            [
                'user_id'=>$this->user['user_id'],
                'is_bind'=>1
            ]
        )->select();

        $filterServerList = [];
        $gameDetail = Db::name('game_build')->where(['id'=>$param['game_id']])->find();
        if(!isset($gameDetail['id'])) return $this->result([],0, '该游戏不存在!', 'json',[], 'status');
        foreach ($bindServerList as $key => $value) {
            if($bindServerList[$key]['id'] == $gameDetail['server_id']){
                array_push($filterServerList, $bindServerList[$key]);
            }
        }

        $this->result(['list1'=>$unbindServerList, 'list2'=>$filterServerList],1, '获取服务器列表成功!', 'json',[], 'status');
    }

    public function bindServer (){
        $params = Request::instance()->param();
        if(!isset($params['serverlist']) || !isset($params['game_id'])) return $this->result([],0, '参数不完整!', 'json',[], 'status');

            
        $serverParams = $params['serverlist'];
        $place_result = str_replace('&quot;','"', $serverParams);
        $decode_result = json_decode($place_result, true);
        if($decode_result['order_status'] == 0) $this->result([],0, '该服务器未完成支付，暂不可绑定!', 'json',[], 'status');
        
        // Db::name('game_build')->where(['id'=>$params['game_id']])->update(['server_id'=>$decode_result['id']]);
        Db::name('game_build')->where(['id'=>$params['game_id']])->update(['server_id'=>$decode_result['id']]);
        Db::name('server')->where(['id'=>$decode_result['id']])->update(['is_bind'=>1]);

        $this->result([],1, '绑定成功!', 'json',[], 'status');
    }

    public function unbindServer (){
        $params = Request::instance()->param();
        if(!isset($params['serverlist']) || !isset($params['game_id'])) return $this->result([],0, '参数不完整!', 'json',[], 'status');

        $serverParams = $params['serverlist'];
        $place_result = str_replace('&quot;','"', $serverParams);
        $decode_result = json_decode($place_result, true);
        Db::name('game_build')->where(['id'=>$decode_result['id']])->update(
            ['is_bind'=>0, 'game_id'=>$params['game_id']]
        );

        $this->result([],1, '解绑成功!', 'json',[], 'status');   
    }

    public function saveServerConfigInfo (){
        $param = Request::instance()->param();
        $stepId = isset($param['stepId']) ? $param['stepId'] : false;
        if(!$stepId) return $this->result([],0,'stepId不能为空','json','status');
        $noTokenParams = $this->removeArrayItemByName($param, 'token');
        $newParams = $this->removeArrayItemByName($noTokenParams, 'stepId');

        Db::name('game_build')
                ->where('id', $stepId)
                ->update(['package_status'=>'0']);
        $serverId = Db::name('server')->insertGetId(array_merge($newParams, ['user_id'=>$this->user['user_id']]));
        $buildData = Db::name('game_build')->where(['id'=>$stepId])->find();
        $price = $param['server_capacity'] + $param['server_time'] + $param['net_wide'];
        //现带宽，每一M，一元，如需修改需要乘以相应倍数
        $this->calcTotalPrice($buildData, $stepId, ['serverFlag'=>true, 'price'=>$price]);
        Db::name('server')->where(['id'=>$serverId])->update(['price'=>$price]);

        $this->result([],1,'服务器配置成功!','json',[],'status');
    }

    public function getPackagedGameList (){
        $param = Request::instance()->param();        
        $gameList = Db::name('game_build')->order('id desc')
                    ->where(['user_id'=> $this->user['user_id'], 'is_complete'=>1])->select();
        $result = $this->queryImageResource($gameList, ['icon_id']);
        $this->result($result,1,'请求成功!','json',[], 'status');
    }

    public function gameOperate (){
        $param = Request::instance()->param();
        if(!isset($param['gameId']) || !isset($param['status'])){
           return $this->result($result,0,'参数不完整','json',[], 'status');
        }

        Db::name('game_list')->where('id', $param['gameId'])
                             ->update(['enable_i'=>$param['status']]);

        $this->result([],1,'游戏'.($param['status'] == 0 ? '关闭' : '开启').'成功!','json',[], 'status');
    }

    public function checkOrder () {
        $param = Request::instance()->param();
        if(!isset($param['id'])){
           return $this->result($result,0,'ID不能为空','json',[], 'status');
        }        

        $findResult = Db::name('game_build')->where('id', $param['id'])->find();
        if($findResult){
            $status = $findResult['order_status'];
            if($status == 1) return $this->result($result,1,'订单已完成!','json',[], 'status');
            else return $this->result([],0,'订单未完成,请重新支付!','json',[], 'status');
        }else{
            return $this->result([],0,'未找到订单!','json',[], 'status');
        }
    }

    public function checkOrderStatusByUserId () {
        $param = Request::instance()->param();
        $gameList = Db::name('game_build')->where(['user_id'=> $this->user['user_id'], 'order_status'=>0])->select();
        if(sizeof($gameList) > 0){
           return $this->result([],0,'您有未完成订单，请处理后在提交新订单!','json',[], 'status');
        }else{
           return $this->result([],1,'无未完成订单，可以支付!','json',[], 'status');
        }
    }

    public function giveUpOrderByOrderId () {
        $param = Request::instance()->param();
        if(!isset($param['id'])){
           return $this->result($result,0,'ID不能为空','json',[], 'status');
        }

        $result = Db::name('game_build')->where('id', $param['id'])->delete();
        
        $this->result([],($result == 0 ? 0 : 1),($result == 0 ? '删除失败' : '删除成功'),'json',[], 'status');
    }
    public function complateOrder (){
        $param = Request::instance()->param();
        if(!isset($param['orderId'])) return $this->result([],0,'orderId不能为空','json',[], 'status');

        $gameInfo = Db::name('game_build')->where(['id'=>$param['orderId']])->find();
        if(doubleval($gameInfo['price']) <= 0){
            Db::name('game_build')->where(['id'=>$param['orderId']])->update(['order_status'=>1]);
            $this->result([],1, '操作成功','json',[], 'status');
        }else{
            $this->result([],'非法操作','json',[], 'status');
        }
    }

    public function getPromptmessage (){
        $this->result($this->promptmessageConfig,1,'请求成功','json',[], 'status');       
    }

    private function array2Map($list,$key){
        $map = [];
        foreach ($list as $val){
            $map[$val[$key]] = $val;
        }
        return $map;
    }

    private function queryImageResource($gameList,$fields=[]){
        $result = [];   
        $ids = [];
        foreach ($gameList as $value) {
            foreach ($fields as $key){
                $ids[] = $value[$key];
            }
        }

        $fieldsMapping = [
            'logo_id'=>'logo_url',
            'theme_id'=>'theme_url',
            'loading_id'=>'loading_url',
            'icon_id'=>'icon_url'
        ];
        
        $data = Db::name('game_resource')->field(['file_path', 'id'])->whereIn('id', $ids)->select();
        $map = $this->array2Map($data, 'id');

        foreach ($gameList as $value) {
            foreach ($fields as $key) {
                $value[$fieldsMapping[$key]] = cmf_get_image_preview_url($map[$value[$key]]['file_path']);
            }
            array_push($result, $value);
        }
        return $result;
    }

    private function addFields($fields){
        $people_num = [];
        foreach ($fields as $key => $value) {
            $keys = array_keys($fields[$key]);
            foreach ($keys as $value){
                if(preg_match('/^num/i', $value)){
                    array_push($people_num, [
                        'place'=>$fields[$key]['place'],
                        'name'=>$value,
                        'value'=>$fields[$key][$value]
                    ]);
                };
            }
        }
        return $people_num;
    }
}
